import axios from "axios";
import { getToken } from '@/utils/auth'
import { ElMessage } from "element-plus";

/* 这里会出现错误信息，因为vite在进行热更新的时候会一致进行巡检，如何在此引入useRouter来作为路由跳转的介质，由于useRouter只能在setup中使用所有就会出现警告信息 */
import router from '../router'


const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASEURL
    // timeout:5000
})

request.interceptors.request.use(config => {
    const token = getToken()
    if (token) config.headers['Authorization'] = token
    return config
})

request.interceptors.response.use(data => {
    return data.data
}, async err => {
    if (err && err.response && err.response.status === 401) {
        localStorage.removeItem('menus')
        localStorage.removeItem('routes')
        localStorage.removeItem('profile')
        localStorage.removeItem('🎈token')
        router.push('/login')
        ElMessage.error(err.response.data.message)
    }
    if (err && err.response && err.response.status === 402 && err.response.data.message) {
        ElMessage.error(err.response.data.message)
    }
    return Promise.reject(err)
})

export default request